const User = require('../models/User');
const { StatusCodes } = require('http-status-codes');

const getUsers = async (req, res) => {
   let query = {};
   const keyword = req.query.keyword;
   let users = [];
   if (keyword && keyword !== '') {
      query = {
         $or: [{ username: keyword }, { phone: keyword }],
      };
      users = await User.find(query).select('-password -__v');
   } else {
      if (req.user.username === 'sanhuamao1') {
         users = await User.find().select('-password -__v');
      }
   }

   res.status(StatusCodes.OK).json({
      data: {
         list: users,
         total: users.length,
      },
   });
};

const getUser = async (req, res) => {
   const user = await User.findOne({
      _id: req.user.userId,
   }).select('-password -__v');
   res.status(StatusCodes.OK).json({
      data: user,
   });
};

const updateUser = async (req, res) => {
   const { password, ...rest } = req.body;
   await User.findOneAndUpdate(
      {
         _id: req.user.userId,
      },
      rest,
      {
         runValidators: true,
      }
   ).select('-password');
   res.status(StatusCodes.OK).json({
      msg: '更新成功',
   });
};

const removeUser = async (req, res) => {
   const user = await User.findByIdAndDelete(req.params.id).select('-password');
   res.status(StatusCodes.OK).json({
      data: user,
      msg: '删除成功',
   });
};

const updateAvatar = async (req, res) => {
   await User.findByIdAndUpdate(req.user.userId, {
      avatar: req.body.avatar,
   });
   res.status(StatusCodes.OK).json({
      msg: '更新成功',
   });
};

const updateUsername = async (req, res) => {
   await User.findByIdAndUpdate(
      req.user.userId,
      {
         username: req.body.username,
      },
      {
         runValidators: true,
      }
   );
   res.status(StatusCodes.OK).json({
      msg: '更新成功',
   });
};

const updateMainGroup = async (req, res) => {
   await User.findByIdAndUpdate(
      req.user.userId,
      {
         mainGroup: req.body.mainGroup,
      },
      {
         new: true,
         runValidators: true,
      }
   );
   res.status(StatusCodes.OK).json({
      msg: '更新成功',
   });
};

module.exports = {
   getUsers,
   getUser,
   updateUser,
   removeUser,
   updateAvatar,
   updateUsername,
   updateMainGroup,
};
